#include <optional>
#include <nice2d/sprite.h>
#include <nice2d/actions/fadeinaction.h>

class FadeinActionData
{
public:
    std::optional<float> vel;
};

FadeinAction::FadeinAction(float duration):
    FiniteTimeAction(duration),
    data(new FadeinActionData())
{
}

FadeinAction::~FadeinAction()
{
}

void FadeinAction::update(float deltaTime)
{
    auto owner = getOwner();
    if (owner.expired())
        return;

    auto target = std::dynamic_pointer_cast<Sprite>(owner.lock());
    assert(target && "FadeinAction's owner must be sprite!");

    if (!data->vel.has_value()) {
        data->vel = 1.0f / getDuration();
        auto color = target->getSpriteColor();
        color.a = 0;
        target->setSpriteColor(color);
    }

    if (data->vel.has_value()) {
        auto color = target->getSpriteColor();
        int32_t alpha = color.a + 255 * data->vel.value() * deltaTime;
        if (alpha >= 255) {
            stop();
        } else {
            color.a = alpha;
            target->setSpriteColor(color);
        }
    }
}
